package main

import (
	"fmt"
	"sync"
	"time"
)

//打印1-1000000之间的素数

func pushNum(cacheIntChan chan int) {
	for i := 2; i <= 10000000; i++ {
		cacheIntChan <- i
	}
	close(cacheIntChan)
	wg.Done()
}

func cachePrime(cachePrimeChan, cacheIntChan chan int, exitChan chan bool) {
	for num := range cacheIntChan {
		var flag = true
		for i := 2; i < num; i++ {
			if num%i == 0 {
				flag = false
				break
			}
		}
		if flag {
			cachePrimeChan <- num
		}
	}
	exitChan <- true
	wg.Done()
}

func printPrime(cachePrimeChan chan int) {
	for prime := range cachePrimeChan {
		<-cachePrimeChan
		fmt.Println(prime)
	}
	wg.Done()
}

var wg sync.WaitGroup

func main() {
	var cacheIntChan = make(chan int, 100000)
	var cachePrimeChan = make(chan int, 100000)
	var exitChan = make(chan bool, 16)

	var start = time.Now().Unix()
	wg.Add(1)
	go pushNum(cacheIntChan)

	for i := 0; i < 16; i++ {
		wg.Add(1)
		go cachePrime(cachePrimeChan, cacheIntChan, exitChan)
	}

	wg.Add(1)
	go func() {
		for i := 0; i < 16; i++ {
			<-exitChan
		}
		close(cachePrimeChan)
		wg.Done()
	}()

	wg.Add(1)
	go printPrime(cachePrimeChan)

	wg.Wait()
	var end = time.Now().Unix()
	fmt.Printf("花费时间s:%v\n", end-start)
}
